{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from PIL import Image\n",
    "import torch.nn as nn\n",
    "from torchvision import models\n",
    "import torch\n",
    "\n",
    "resnet101 = models.resnet101(pretrained=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"./E1.png\" alt=\"图片替换文本\" width=\"500\" height=\"313\" align=\"bottom\" />"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SEB(nn.Module):\n",
    "    def __init__(self, in_channels, out_channels):\n",
    "        super(SEB, self).__init__()\n",
    "        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1,padding=1)\n",
    "        self.upsample = nn.Upsample(scale_factor=2, mode=\"bilinear\")\n",
    "\n",
    "    def forward(self, x):\n",
    "        x1, x2 = x\n",
    "        return x1 * self.upsample(self.conv(x2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"./E3.png\" alt=\"图片替换文本\" width=\"500\" height=\"313\" align=\"bottom\" />"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ECRE(nn.Module):\n",
    "    def __init__(self, in_c, up_scale=2):\n",
    "        super(ECRE, self).__init__()\n",
    "        self.ecre = nn.Sequential(nn.Conv2d(in_c, in_c * up_scale * up_scale, kernel_size=3, stride=1, padding=1),\n",
    "                                  nn.BatchNorm2d(in_c * up_scale * up_scale),\n",
    "                                  nn.PixelShuffle(up_scale))\n",
    "\n",
    "    def forward(self, input_):\n",
    "        return self.ecre(input_)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"./E4.png\" alt=\"图片替换文本\" width=\"500\" height=\"313\" align=\"bottom\" />"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "class _GlobalConvModule(nn.Module):\n",
    "    def __init__(self, in_channels, num_class, k=15):\n",
    "        super(_GlobalConvModule, self).__init__()\n",
    "\n",
    "        pad = (k-1) // 2\n",
    "\n",
    "        self.conv1 = nn.Sequential(nn.Conv2d(in_channels, num_class, kernel_size=(1, k), padding=(0, pad), bias=False),\n",
    "                                   nn.Conv2d(num_class, num_class, kernel_size=(k, 1), padding=(pad, 0), bias=False))\n",
    "\n",
    "        self.conv2 = nn.Sequential(nn.Conv2d(in_channels, num_class, kernel_size=(k, 1), padding=(pad, 0), bias=False),\n",
    "                                   nn.Conv2d(num_class, num_class, kernel_size=(1, k), padding=(0, pad), bias=False))\n",
    "\n",
    "    def forward(self, x):\n",
    "\n",
    "        x1 = self.conv1(x)\n",
    "        x2 = self.conv2(x)\n",
    "\n",
    "        assert x1.shape == x2.shape\n",
    "\n",
    "        return x1 + x2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"./E2.png\" alt=\"图片替换文本\" width=\"500\" height=\"313\" align=\"bottom\" />"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "class GCNFuse(nn.Module):\n",
    "    def __init__(self, num_classes=21):\n",
    "        super(GCNFuse, self).__init__()\n",
    "        self.num_classes = num_classes\n",
    "        dap_k = 3\n",
    "        self.resnet_features = models.resnet101(pretrained=False)\n",
    "        self.layer0 = nn.Sequential(self.resnet_features.conv1, self.resnet_features.bn1, self.resnet_features.relu)\n",
    "        self.layer1 = nn.Sequential(self.resnet_features.maxpool, self.resnet_features.layer1)\n",
    "        self.layer2 = self.resnet_features.layer2\n",
    "        self.layer3 = self.resnet_features.layer3\n",
    "        self.layer4 = self.resnet_features.layer4\n",
    "\n",
    "        self.gcm1 = _GlobalConvModule(2048, num_classes * 4)\n",
    "        self.gcm2 = _GlobalConvModule(1024, num_classes)\n",
    "        self.gcm3 = _GlobalConvModule(512, num_classes * dap_k**2)\n",
    "        self.gcm4 = _GlobalConvModule(256, num_classes * dap_k**2)\n",
    "\n",
    "        self.deconv1 = ECRE(num_classes)\n",
    "        # self.deconv1 = nn.ConvTranspose2d(num_classes, num_classes * dap_k**2, kernel_size=4, stride=2, padding=1, bias=False)\n",
    "        self.deconv2 = nn.ConvTranspose2d(num_classes, num_classes * dap_k**2, kernel_size=4, stride=2, padding=1, bias=False)\n",
    "        self.deconv3 = nn.ConvTranspose2d(num_classes * dap_k**2, num_classes * dap_k**2, kernel_size=4, stride=2, padding=1, bias=False)\n",
    "        self.deconv4 = nn.ConvTranspose2d(num_classes * dap_k**2, num_classes * dap_k**2, kernel_size=4, stride=2, padding=1, bias=False)\n",
    "        self.deconv5 = nn.ConvTranspose2d(num_classes * dap_k**2, num_classes * dap_k**2, kernel_size=4, stride=2, padding=1, bias=False)\n",
    "\n",
    "        self.ecre = nn.PixelShuffle(2)\n",
    "\n",
    "        self.seb1 = SEB(2048, 1024)\n",
    "        self.seb2 = SEB(3072, 512)\n",
    "        self.seb3 = SEB(3584, 256)\n",
    "\n",
    "        self.upsample2 = nn.Upsample(scale_factor=2, mode=\"bilinear\")\n",
    "        self.upsample4 = nn.Upsample(scale_factor=4, mode=\"bilinear\")\n",
    "\n",
    "        self.DAP = nn.Sequential(\n",
    "            nn.PixelShuffle(dap_k),\n",
    "            nn.AvgPool2d((dap_k,dap_k))\n",
    "        )\n",
    "\n",
    "    def forward(self, x):\n",
    "        # suppose input = x , if x 512\n",
    "        f0 = self.layer0(x)  # 256\n",
    "        f1 = self.layer1(f0)  # 128\n",
    "        print (f1.size())\n",
    "        f2 = self.layer2(f1)  # 64\n",
    "        print (f2.size())\n",
    "        f3 = self.layer3(f2)  # 32\n",
    "        print (f3.size())\n",
    "        f4 = self.layer4(f3)  # 16\n",
    "        print (f4.size())\n",
    "        x = self.gcm1(f4)\n",
    "        out1 = self.ecre(x)\n",
    "        seb1 = self.seb1([f3, f4])\n",
    "        gcn1 = self.gcm2(seb1)\n",
    "\n",
    "        seb2 = self.seb2([f2, torch.cat([f3, self.upsample2(f4)], dim=1)])\n",
    "        gcn2 = self.gcm3(seb2)\n",
    "\n",
    "        seb3 = self.seb3([f1, torch.cat([f2, self.upsample2(f3), self.upsample4(f4)], dim=1)])\n",
    "        gcn3 = self.gcm4(seb3)\n",
    "\n",
    "        y = self.deconv2(gcn1 + out1)\n",
    "        y = self.deconv3(gcn2 + y)\n",
    "        y = self.deconv4(gcn3 + y)\n",
    "        y = self.deconv5(y)\n",
    "        y = self.DAP(y)\n",
    "        return y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([1, 256, 8, 8])\n",
      "torch.Size([1, 512, 4, 4])\n",
      "torch.Size([1, 1024, 2, 2])\n",
      "torch.Size([1, 2048, 1, 1])\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\nanfe\\anaconda3\\lib\\site-packages\\torch\\nn\\functional.py:2539: UserWarning: Default upsampling behavior when mode=bilinear is changed to align_corners=False since 0.4.0. Please specify align_corners=True if the old behavior is desired. See the documentation of nn.Upsample for details.\n",
      "  \"See the documentation of nn.Upsample for details.\".format(mode))\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "result: torch.Size([1, 21, 32, 32])\n"
     ]
    }
   ],
   "source": [
    "if __name__ == '__main__':\n",
    "    model = GCNFuse(21)\n",
    "    model.eval()\n",
    "    image = torch.randn(1, 3, 32, 32)\n",
    "    res1 = model(image)\n",
    "    print('result:', res1.size())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
